//
//  DownLoadImageTools.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/17.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

class DownLoadImageTools: NSObject {

    func downLoadImage ( imageUrl : NSString , finishedBlock : ( image : UIImage? ) -> ()) -> () {
        
        let image = imageCacheDictionary[imageUrl as String];
        
        if image != nil {
            
            print("内存载入图片")
            
            resultImage = image as! UIImage
            
            finishedBlock(image: resultImage) ;
            
            return
            
        }else{
            
            print("检测沙盒 == : \(imageUrl.appendCachePath())")
            
            //尝试从沙盒中取出图片
            
            //            UIImage * sadboxImage = [UIImage imageWithContentsOfFile:model.icon.appendCachePath] ;
            
            let sadboxImage : UIImage? = UIImage(contentsOfFile: (imageUrl.appendCachePath() as String))
            
            if sadboxImage != nil {
                
                print("从沙盒中取出图片")
                
                //                [self.imageCache setObject:sadboxImage forKey:model.icon];
                
                imageCacheDictionary[imageUrl as String] = sadboxImage!
                
                resultImage = sadboxImage! as UIImage
                
                finishedBlock(image: resultImage)
                
                return
            }
            
        }
        
        if operationCacheDictionary[imageUrl as String] != nil {
            
            //self.operationCache[model.icon]
            
            print("正在下载中........")
            
            finishedBlock(image: nil)
            
        }
        
        //开始下载图片的进程
        let downloadImageOperation : NSBlockOperation = NSBlockOperation { () -> Void in
            
            print("开始下载图片")
            
            let imageURL = NSURL(string: imageUrl as String)
            
            let imageData = NSData(contentsOfURL: imageURL!)
            
            let image : UIImage? = UIImage(data: imageData!)
            
            if image != nil {
                
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    
                    self.operationCacheDictionary.removeValueForKey(imageUrl as String)
                    
                    imageData?.writeToFile(imageUrl.appendCachePath() as String, atomically: true)
                    
                    if image != nil {
                        
                        self.imageCacheDictionary[imageUrl as String] = image
                        
                        self.resultImage = self.imageCacheDictionary[imageUrl as String] as! UIImage
                        
                        print("-----------图片下载完成")
                        
                        finishedBlock(image: self.resultImage)
                        
                        return
                        
                    }
                    
                })
                
            }else{
                
                print("URL 地址无法获取二进制图片数据")
                
            }
            
        }
        
        operationCacheDictionary[imageUrl as String] = downloadImageOperation
        
        myQueue.addOperation(downloadImageOperation)
        
            
//        if (imageCacheDictionary[imageUrl as String] != nil) {
//            
//            let image = imageCacheDictionary[image as! String]
//            
//            resultImage = image as! UIImage
//            
//        }else{
//            
//            print("下载错误....")
//            
//        }
        
        
    }

    
//    func downLoadImage( imageUrl : NSString ) -> (UIImage?) {
//        
//        let image = imageCacheDictionary[imageUrl as String];
//        
//        if image != nil {
//            
//            print("内存载入图片")
//            
//            resultImage = image as! UIImage
//            
//            return resultImage ;
//            
//        }else{
//            
//            print("检测沙盒")
//            
//            //尝试从沙盒中取出图片
//            
////            UIImage * sadboxImage = [UIImage imageWithContentsOfFile:model.icon.appendCachePath] ;
//            
//            let sadboxImage : UIImage? = UIImage(contentsOfFile: (imageUrl.appendCachePath() as String))
//            
//            if sadboxImage != nil {
//                
//                print("从沙盒中取出图片")
//                
////                [self.imageCache setObject:sadboxImage forKey:model.icon];
//                
//                imageCacheDictionary[imageUrl as String] = sadboxImage!
//                
//                resultImage = sadboxImage! as UIImage
//                
//                return resultImage
//            }
//            
//        }
//        
//        if operationCacheDictionary[imageUrl as String] != nil {
//            
//            //self.operationCache[model.icon]
//            
//            print("正在下载中........")
//            
//            return nil ;
//            
//        }
//        
//        dispatch_group_enter(group)
//        
//        //开始下载图片的进程
//        let downloadImageOperation : NSBlockOperation = NSBlockOperation { () -> Void in
//            
//            print("开始下载图片")
//            
//            let imageURL = NSURL(string: imageUrl as String)
//            
//            let imageData = NSData(contentsOfURL: imageURL!)
//            
//            let image : UIImage? = UIImage(data: imageData!)
//            
//            if image != nil {
//                
//                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
//                    
//                    self.operationCacheDictionary.removeValueForKey(imageUrl as String)
//                    
//                    imageData?.writeToFile(imageUrl.appendCachePath() as String, atomically: true)
//                    
//                    if image != nil {
//                    
//                        self.imageCacheDictionary[imageUrl as String] = image
//                        
//                    }
//                    
//                })
//            
//            }else{
//            
//                print("URL 地址无法获取二进制图片数据")
//            
//            }
//            
//            dispatch_group_leave(self.group)
//            
//        }
//        
//        operationCacheDictionary[imageUrl as String] = downloadImageOperation
//        
//        myQueue.addOperation(downloadImageOperation)
//        
//        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            
//            if (self.imageCacheDictionary[imageUrl as String] != nil) {
//                
//                let image = self.imageCacheDictionary[image as! String]
//                
//                self.resultImage = image as! UIImage
//                
//            }else{
//            
//                print("下载错误....")
//            
//            }
//        
//        }
//        
//        return resultImage
//        
//}
    
    lazy var myQueue : NSOperationQueue = {
        
        let myQ = NSOperationQueue()
        
        return myQ
        
    }()
    
    //图片缓存字典
    lazy var imageCacheDictionary : [String : AnyObject] = [String : AnyObject]()
    
    //线程操作缓存字典
    lazy var operationCacheDictionary : [String : AnyObject] = [String : AnyObject]()

    lazy var resultImage : UIImage = UIImage()
    
}




//    NSBlockOperation * downloadImageOp = [NSBlockOperation blockOperationWithBlock:^{
//    
//    NSLog(@" >>>>>开始下载图片 %@ " , model.name);
//    
//    [NSThread sleepForTimeInterval:3];
//    
//    //分支下载图片
//    NSString * imageStr = model.icon;
//    
//    NSURL * imageUrl = [NSURL URLWithString:imageStr];
//    
//    NSData * imageData = [NSData dataWithContentsOfURL:imageUrl];
//    
//    UIImage * image = [UIImage imageWithData:imageData];
//    
//    //下载完成之后通知主线程
//    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//    
//    [self.operationCache removeObjectForKey:model.icon] ;
//    
//    //保存到沙盒(Save in sadbox)
//    
//    [imageData writeToFile:model.icon.appendCachePath atomically:NO];
//    
//    if (image)
//    [self.imageCache setObject:image forKeyedSubscript:model.icon];
//    
//    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//    
//    }];
//    
//    }];
//    
//    [self.operationCache setObject:downloadImageOp forKeyedSubscript:model.icon];
//    
//    [self.myQueue addOperation:downloadImageOp];
//    
//}


